import json
import re

from django.db.models import Q
from fdfs_client.client import Fdfs_client
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from django.conf import settings
from apps.goods.models import SPU, Brand, GoodsCategory
from apps.meiduo_admin.serializers.spus_serializers import SPUserializer, GoodsBrandserializer, SPUCategorieSerializer
from apps.meiduo_admin.utils.pagenum import PageNum

# 获取spu数据

class SpusView(ModelViewSet):
    serializer_class = SPUserializer
    queryset = SPU.objects.all()
    pagination_class = PageNum
    def update(self, request, *args, **kwargs):
        print("-------------------------")
        a = request.data
        print(a,type(a))
        instance = self.get_object()
        spu = SPU.objects.get(id=instance.id)
        #前端图片地址列表
        qian_detail = request.data.get("desc_detail")
        pat = r'img src="http://image.meiduo.site:8888/(.{51})" />'
        qian_detail_list = re.compile(pat).findall(str(qian_detail))
        # 数据库图片地址列表
        desc_detail = spu.desc_detail
        # pat = r'img src="http://image.meiduo.site:8888/(group\d/.{3}/\d{2}/\d{2}/[^"]+)" />'
        pat = r'img src="http://image.meiduo.site:8888/(.{51})" />'
        desc_detail_list = re.compile(pat).findall(str(desc_detail))
        # 如果数据库的数据不在前端传输的列表中  说明前端已经删除照片  则链接远程  删除照片
        for i in range(0,len(desc_detail_list)):
            shu_a = desc_detail_list[i]
            if shu_a not in  qian_detail_list:
                image_client = Fdfs_client(settings.FASTDFS_PATH)
                # instance.image.name获取图片名称字符串
                image_client.delete_file(shu_a)
# ====================================
        # 前端图片地址列表
        qian_desc_pack = request.data.get("desc_pack")
        # print(qian_desc_pack)
        pat = r'img src="http://image.meiduo.site:8888/(.{51})" />'
        qian_desc_pack_list = re.compile(pat).findall(str(qian_desc_pack))
        # 数据库图片地址列表
        desc_pack = spu.desc_pack
        # pat = r'img src="http://image.meiduo.site:8888/(group\d/.{3}/\d{2}/\d{2}/[^"]+)" />'
        pat = r'img src="http://image.meiduo.site:8888/(.{51})" />'
        desc_pack_list = re.compile(pat).findall(str(desc_pack))
        # 如果数据库的数据不在前端传输的列表中  说明前端已经删除照片  则链接远程  删除照片
        for i in range(0, len(desc_pack_list)):
            shu_a = desc_pack_list[i]
            if shu_a not in qian_desc_pack_list:
                image_client = Fdfs_client(settings.FASTDFS_PATH)
                # instance.image.name获取图片名称字符串
                image_client.delete_file(shu_a)
# ====================================
        # 前端图片地址列表
        qian_desc_service = request.data.get("desc_service")
        # print(qian_desc_service)
        pat = r'img src="http://image.meiduo.site:8888/(.{51})" />'
        qian_desc_service_list = re.compile(pat).findall(str(qian_desc_service))
        # 数据库图片地址列表
        desc_service = spu.desc_service
        # pat = r'img src="http://image.meiduo.site:8888/(group\d/.{3}/\d{2}/\d{2}/[^"]+)" />'
        pat = r'img src="http://image.meiduo.site:8888/(.{51})" />'
        desc_service_list = re.compile(pat).findall(str(desc_service))
        # 如果数据库的数据不在前端传输的列表中  说明前端已经删除照片  则链接远程  删除照片
        for i in range(0, len(desc_service_list)):
            shu_a = desc_service_list[i]
            if shu_a not in qian_desc_service_list:
                image_client = Fdfs_client(settings.FASTDFS_PATH)
                # instance.image.name获取图片名称字符串
                image_client.delete_file(shu_a)
        SPU.objects.filter(id=instance.id).update(**a)
        instance = SPU.objects.get(id=instance.id)
        # name = request.data.get("name")
        # desc_service = request.data.get("desc_service")
        # category3_id = request.data.get("category3_id")
        # brand_id = request.data.get("brand_id")
        # desc_detail = request.data.get("desc_detail")
        # category1_id = request.data.get("category1_id")
        # desc_pack = request.data.get("desc_pack")
        # instance.name=name
        # instance.desc_service=desc_service
        # instance.category3_id=category3_id
        # instance.brand_id=brand_id
        # instance.desc_detail=desc_detail
        # instance.category1_id=category1_id
        # instance.desc_pack=desc_pack
        # instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)
        # 如果前端传的照片不再数据库中  说明有新增数据  则链接远程 上传图片
        # for i in range(0, len(qian_detail_list)):
        #     qian_a = qian_detail_list[i]
        #     if qian_a not in  desc_detail_list:
        #         image_client = Fdfs_client(settings.FASTDFS_PATH)
        #         data = image_client.upload_by_buffer(qian_a)
        #         image_url = data.get("Remote file_id")
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        desc_pack = instance.desc_pack
        desc_service =  instance.desc_service
        desc_detail = instance.desc_detail
        if "img" in desc_detail:
            pat = r'img src="http://image.meiduo.site:8888/(.{51})" />'
            desc_detail_list = re.compile(pat).findall(str(desc_detail))
            # 如果数据库的数据不在前端传输的列表中  说明前端已经删除照片  则链接远程  删除照片
            for i in range(0, len(desc_detail_list)):
                shu_a = desc_detail_list[i]
                image_client = Fdfs_client(settings.FASTDFS_PATH)
                # instance.image.name获取图片名称字符串
                image_client.delete_file(shu_a)
        if "img" in desc_service:
            pat = r'img src="http://image.meiduo.site:8888/(.{51})" />'
            desc_service_list = re.compile(pat).findall(str(desc_service))
            # 如果数据库的数据不在前端传输的列表中  说明前端已经删除照片  则链接远程  删除照片
            for i in range(0, len(desc_service_list)):
                shu_a = desc_service_list[i]
                image_client = Fdfs_client(settings.FASTDFS_PATH)
                # instance.image.name获取图片名称字符串
                image_client.delete_file(shu_a)
        if "img" in desc_pack:
            pat = r'img src="http://image.meiduo.site:8888/(.{51})" />'
            desc_pack_list = re.compile(pat).findall(str(desc_pack))
            for i in range(0, len(desc_pack_list)):
                shu_a = desc_pack_list[i]
                image_client = Fdfs_client(settings.FASTDFS_PATH)
                # instance.image.name获取图片名称字符串
                image_client.delete_file(shu_a)
        instance.delete()
        return Response(status=204)

# @action(methods=['post'], detail=False)
# def create(self, request, *args, **kwargs):
#     print("===================")
#     image = request.data.get("image")
#     # 验证数据
#     if not all([image]):
#         return Response({"detial": "数据不完整"}, status=400)
#     # 处理
#     image_client = Fdfs_client(settings.FASTDFS_PATH)
#     # 上传图片   文件不在本地时用upload_by_buffer
#     data = image_client.upload_by_buffer(image.read())
#     image_name = data.get("Remote file_id")
#     return image_name

# 获取品牌分类
class GoodsBrandsView(ListAPIView):
    serializer_class = GoodsBrandserializer
    queryset = Brand.objects.all()


# 获取商品的一级分类
class GoodsCategoriesOneView(ListAPIView):
    serializer_class = SPUCategorieSerializer
    queryset = GoodsCategory.objects.filter(parent__isnull=True)


# 获取商品的二三级分类
class GoodsCategoriesTwoThreeView(ListAPIView):
    serializer_class = SPUCategorieSerializer

    def get_queryset(self):
        # 接收查询参数表单传参
        # pk = self.request.query_params.get("pk")
        # args===查询位置参数  kwargs==查询关键字参数
        # 接受路由传参
        pk = self.kwargs.get("pk")
        queryset = GoodsCategory.objects.filter(parent_id=pk)
        return queryset


# 上传照片
class GoodsImageiew(APIView):
    def post(self, request):
        # print(request.data)
        image = request.data.get("image")
        print(image)
        # image = request.POST.get("filename")
        # 验证数据
        if not all([image]):
            return Response({"detial": "数据不完整"}, status=400)
        # 处理
        image_client = Fdfs_client(settings.FASTDFS_PATH)
        # 上传图片   文件不在本地时用upload_by_buffer
        data = image_client.upload_by_buffer(image.read())
        image_name = data.get("Remote file_id")
        print(image_name)
        return Response({
            'img_url': settings.FDFS_URL + image_name
        })

        #
        # def create(self, validated_data):
        #        image = GoodsImageiew()
        #        image_url = image.post(self.request)
        #        validated_data["desc_detail"] = image_url
        #        instance = SPU.objects.create(**validated_data)
        #        return instance
